//
//  iCarouselExampleViewController.m
//  iCarouselExample
//
//  Created by Nick Lockwood on 03/04/2011.
//  Copyright 2011 Charcoal Design. All rights reserved.
//


#import "iCarouselViewController.h"
#import "iCarousel.h"
//#import "define.h"
//#import "Global.h"
#import "AppDelegate.h"
//#import "UIButton+WebCache.h"
#import "Constant.h"

#define SCROLL_BASE_TAG         100
#define PAGE_BASE_TAG           200

#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

#define NUMBER_OF_ITEMS (IS_IPAD? 10: 10)
#define NUMBER_OF_VISIBLE_ITEMS (IS_IPAD? 19: 10)
#define ITEM_SPACING (IS_IPAD? 280: 150)
#define INCLUDE_PLACEHOLDERS YES


@interface iCarouselViewController () <iCarouselDataSource, iCarouselDelegate, UIActionSheetDelegate>
{
    int iCurrSelectedItem;
}

@property (nonatomic, retain) iCarousel *carousel;
@property (nonatomic, assign) BOOL wrap;
@property (nonatomic, retain) NSMutableArray *items;
@property (nonatomic, retain) NSMutableArray *carouselImgArr;
@property (nonatomic, retain) NSMutableArray *carouselIDArr;
@end


@implementation iCarouselViewController

@synthesize carousel;
@synthesize carouselImgArr;
@synthesize carouselIDArr;
@synthesize wrap;
@synthesize items;

- (id)initWithData:(NSMutableArray*) dataArr
{
    if ((self = [super init]))
    {
        //set up data
        iCurrSelectedItem = 0;
        
        self.items = [NSMutableArray array];
        for (int i = 0; i < NUMBER_OF_ITEMS; i++)
        {
            [items addObject:[NSNumber numberWithInt:i]];
        }
        carouselImgArr = [[NSMutableArray alloc] initWithArray:dataArr];
            
    }
    return self;
}

- (void)setDataForCarousel:(NSMutableArray*)dataArr
{
    carouselIDArr = [[NSMutableArray alloc] initWithArray:dataArr];
}

- (void)dealloc
{
	//it's a good idea to set these to nil here to avoid
	//sending messages to a deallocated viewcontroller
	carousel.delegate = nil;
	carousel.dataSource = nil;
	
    [carousel release];
	[items release];
    [super dealloc];
}

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    wrap = YES;
	
	//create carousel
	carousel = [[iCarousel alloc] initWithFrame:self.view.bounds];
	carousel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    carousel.type = iCarouselTypeCoverFlow2;
	carousel.delegate = self;
	carousel.dataSource = self;

	//add carousel to view
	[self.view addSubview:carousel];
    [self startScrollCarousel];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.carousel = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}


- (void) startScrollCarousel
{
    scrollTimer = [NSTimer scheduledTimerWithTimeInterval:2.2 target:self selector:@selector(scrollCarousel) userInfo:nil repeats:YES];
}

-(void) scrollCarousel
{
    int index = carousel.currentItemIndex;
    [carousel scrollToItemAtIndex:index+1 duration:1.8];
}

- (IBAction)insertItem
{
    NSInteger index = carousel.currentItemIndex;
    [items insertObject:[NSNumber numberWithInt:carousel.numberOfItems] atIndex:index];
    [carousel insertItemAtIndex:index animated:YES];
}

- (IBAction)removeItem
{
    if (carousel.numberOfItems > 0)
    {
        NSInteger index = carousel.currentItemIndex;
        [carousel removeItemAtIndex:index animated:YES];
        [items removeObjectAtIndex:index];
    }
}

- (CGFloat)carousel:(iCarousel *)carousel valueForTransformOption:(iCarouselTranformOption)option withDefault:(CGFloat)value
{
    switch (option)
    {
        case iCarouselTranformOptionTilt:
        {
            return 0.6f;
        }
        case iCarouselTranformOptionSpacing:
        {
            return 0.38f;
        }
        default:
        {
            return value;
        }
    }
}

#pragma mark -
#pragma mark UIActionSheet methods

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex >= 0)
    {
        //map button index to carousel type
        iCarouselType type = buttonIndex;
        
        //carousel can smoothly animate between types
        [UIView beginAnimations:nil context:nil];
        carousel.type = type;
        [UIView commitAnimations];
    }
}

#pragma mark -
#pragma mark iCarousel methods

- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
    return [items count];
}

- (NSUInteger)numberOfVisibleItemsInCarousel:(iCarousel *)carousel
{
    //limit the number of items views loaded concurrently (for performance reasons)
    return NUMBER_OF_VISIBLE_ITEMS;
}

- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
{
    UIButton *button = (UIButton *)view;
    
	if (button == nil)
	{
        NSString *imagePath = [carouselImgArr objectAtIndex:index];
        NSURL * imageURL = [NSURL URLWithString:imagePath];
		button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTag:SCROLL_BASE_TAG+index];
		//button.frame = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height);
        button.frame = CGRectMake(0.0f, 0.0f, 110, 140);
		//[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        NSString *imageName = [NSString stringWithFormat:@"qnga%d.png",index];
		[button setBackgroundImageWithURL:imageURL placeholderImage:[UIImage imageNamed:imageName]];
        //button.backgroundColor = [UIColor redColor];
		//button.titleLabel.font = [button.titleLabel.font fontWithSize:50];
		[button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
        
        
        if(index==0)
        {
            UIImageView *imgViewBkg = [[UIImageView alloc] initWithFrame:CGRectMake(-10.0f, -7.0f, 130.0f, 156.0f)];
            [imgViewBkg setBackgroundColor:[UIColor clearColor]];
            [imgViewBkg setImage:[UIImage imageNamed:kImgHomeCarouselBorder]];
            [button addSubview:imgViewBkg];
            [imgViewBkg release];
        }
         
	}
	
	//set button label
	//[button setTitle:[NSString stringWithFormat:@"%i", index] forState:UIControlStateNormal];
	
	return button;
}

- (NSUInteger)numberOfPlaceholdersInCarousel:(iCarousel *)carousel
{
	//note: placeholder views are only displayed if wrapping is disabled
	return INCLUDE_PLACEHOLDERS? 2: 0;
}

- (CGFloat)carouselItemWidth:(iCarousel *)carousel
{
    //slightly wider than item view
    return ITEM_SPACING;
}

- (CGFloat)carousel:(iCarousel *)carousel itemAlphaForOffset:(CGFloat)offset
{
	//set opacity based on distance from camera
    return 1.0f - fminf(fmaxf(offset, 0.0f), 1.0f);
}

- (CATransform3D)carousel:(iCarousel *)_carousel itemTransformForOffset:(CGFloat)offset baseTransform:(CATransform3D)transform
{
    //implement 'flip3D' style carousel
    transform = CATransform3DRotate(transform, M_PI / 8.0f, 0.0f, 1.0f, 0.0f);
    return CATransform3DTranslate(transform, 0.0f, 0.0f, offset * carousel.itemWidth);
}

- (BOOL)carouselShouldWrap:(iCarousel *)carousel
{
    //wrap all carousels
    return wrap;
}

- (void)buttonTapped:(UIButton *)sender
{
    //post notification when the carousel is touched
    NSString* strAlert = [NSString stringWithFormat:@"%d", [sender tag]];
    if(scrollTimer)
    {
        [scrollTimer invalidate];
        scrollTimer = nil;
    }
    [[NSNotificationCenter defaultCenter] postNotificationName: CAROUSEL_CLICKED_NOTI object:strAlert];
}

- (void)carouselDidEndScrollingAnimation:(iCarousel *)_carousel
{
    int index = [_carousel currentItemIndex];
    NSString* strAlert = [NSString stringWithFormat:@"%d", index];
    [[NSNotificationCenter defaultCenter] postNotificationName: CAROUSEL_CHANGED_NOTI object:strAlert];
}

- (void)carouselCurrentItemIndexUpdated:(iCarousel *)_carousel
{
    UIView* btnPrevItem = (UIView*)[_carousel viewWithTag:(SCROLL_BASE_TAG+iCurrSelectedItem)];
    [[[btnPrevItem subviews] lastObject] removeFromSuperview];
    
    UIButton* btnCurrItem = (UIButton*)[_carousel currentItemView];
    UIImageView *imgViewBkg = [[UIImageView alloc] initWithFrame:CGRectMake(-10.0f, -7.0f, 130.0f, 156.0f)];
    [imgViewBkg setBackgroundColor:[UIColor clearColor]];
    [imgViewBkg setImage:[UIImage imageNamed:kImgHomeCarouselBorder]];
    [btnCurrItem addSubview:imgViewBkg];
    [imgViewBkg release];
    
    iCurrSelectedItem = [carousel currentItemIndex];

}

@end
